package com.lzdongrui.backend.service.impl;

import java.util.List;

import com.lzdongrui.backend.domain.dto.CollegeDTO;
import com.lzdongrui.backend.domain.vo.CampusVO;
import com.lzdongrui.backend.domain.vo.CollegeVO;
import com.lzdongrui.common.exception.ServiceException;
import com.lzdongrui.common.utils.DateUtils;
import com.lzdongrui.common.utils.StringUtils;
import com.lzdongrui.common.utils.bean.BeanValidators;
import com.lzdongrui.common.utils.snowid.SnowflakeIdWorker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lzdongrui.backend.mapper.CollegeMapper;
import com.lzdongrui.backend.domain.College;
import com.lzdongrui.backend.service.ICollegeService;

import javax.validation.Validator;

/**
 * 学院Service业务层处理
 *
 * @author wyh
 * @date 2023-04-28
 */
@Service
public class CollegeServiceImpl implements ICollegeService {
    private static final Logger log = LoggerFactory.getLogger(CollegeServiceImpl.class);

    @Autowired
    private CollegeMapper collegeMapper;

    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;

    @Autowired
    protected Validator validator;

    /**
     * 查询学院
     *
     * @param id 学院主键
     * @return 学院
     */
    @Override
    public College selectCollegeById(Long id) {
        return collegeMapper.selectCollegeById(id);
    }

    /**
     * 查询学院列表
     *
     * @param collegeDTO 学院
     * @return 学院
     */
    @Override
    public List<CollegeVO> selectCollegeList(CollegeDTO collegeDTO) {
        return collegeMapper.selectCollegeList(collegeDTO);
    }

    @Override
    public List<College> selectCollegeAllList(CollegeDTO collegeDTO) {
        return collegeMapper.selectCollegeAllList(collegeDTO);
    }

    @Override
    public List<College> selectCollegeListByCampusId(College college) {
        return collegeMapper.selectCollegeListByCampusId(college);
    }

    /**
     * 新增学院
     *
     * @param college 学院
     * @return 结果
     */
    @Override
    public int insertCollege(College college) {
        int ret = 0;
        College n = collegeMapper.selectCollegeInfo(college);
        if(StringUtils.isNull(n)){
            college.setId(snowflakeIdWorker.nextId());
            college.setCreateTime(DateUtils.getNowDate());
            ret = collegeMapper.insertCollege(college);
        }else{
            throw new ServiceException("请检查学院代码和名称是否有重复");
        }
        return ret;
    }

    /**
     * 修改学院
     *
     * @param college 学院
     * @return 结果
     */
    @Override
    public int updateCollege(College college) {
        int ret =  0;
        College n = collegeMapper.selectCollegeInfo(college);
        if(n.getId().equals(college.getId())){
            college.setUpdateTime(DateUtils.getNowDate());
            ret = collegeMapper.updateCollege(college);
        }else{
            throw new ServiceException("请检查学院代码和名称是否有重复");
        }
        return ret;
    }

    /**
     * 批量删除学院
     *
     * @param ids 需要删除的学院主键
     * @return 结果
     */
    @Override
    public int deleteCollegeByIds(Long[] ids) {
        return collegeMapper.deleteCollegeByIds(ids);
    }

    /**
     * 删除学院信息
     *
     * @param id 学院主键
     * @return 结果
     */
    @Override
    public int deleteCollegeById(Long id) {
        return collegeMapper.deleteCollegeById(id);
    }

    @Override
    public String importCollege(List<College> colleges, boolean updateSupport, Long operator) {
        if (StringUtils.isNull(colleges) || colleges.size() == 0) {
            throw new ServiceException("导入学院数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (College college : colleges) {
            try {
                //查询学院的数据是否有重复（包含code、名称）
                College n = collegeMapper.selectCollegeInfo(college);
                if (StringUtils.isNull(n)) {
                    college.setId(snowflakeIdWorker.nextId());
                    college.setOperator(operator);
                    BeanValidators.validateWithException(validator, college);
                    this.insertCollege(college);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、学院Code " + college.getCollegeCode() + "、学院 " + college.getName() + " 导入成功");
                } else if (updateSupport) {
                    college.setId(n.getId());
                    college.setOperator(operator);
                    BeanValidators.validateWithException(validator, college);
                    this.updateCollege(college);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、学院Code " + college.getCollegeCode() + "、学院 " + college.getName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、学院 " + college.getName() + " 已存在");
                }
                //返回异常数据
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、学院 " + college.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

}
